package com.practice.references;

import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;

/**
 * 软引用:
 *      1. 堆空间充足时不会被回收
 *      2. 堆空间不足时有可能被回收
 *      3. 若对象没有被回收就可以被应用程序使用
 */
public class SoftReferencesTest {
    public static void main(String[] args) {
        // 强引用
        String a = new String("abc");
        // 软引用
        SoftReference<String> softReference = new SoftReference<>(new String("abc"));

        ReferenceQueue<String> referenceQueue = new ReferenceQueue<>();
        String d = "abc";
        SoftReference<String> c = new SoftReference<>(d, referenceQueue);
        System.out.println(c.get());
        System.out.println(referenceQueue.poll());
        System.out.println("================================");

        d=null;
        System.out.println(c.get());
        System.out.println(referenceQueue.poll());
        System.out.println("================================");

        System.gc();
        System.out.println(c.get());
        System.out.println(referenceQueue.poll());
        System.out.println("================================");

    }
}
